
package com.nikmesoft.android.alwaysontime.activities;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
import com.nikmesoft.android.alwaysontime.R;
import com.nikmesoft.android.alwaysontime.binding.ExtraBinding;
import com.nikmesoft.android.alwaysontime.daos.SmsMainDAO;
import com.nikmesoft.android.alwaysontime.models.SmsMainItem;

public class SMSActivityAdd extends BaseActivity
{	boolean isEdit = false;
	int smsId = 0;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{	super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_smsactivity_add);
		View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.activity_smsactivity_add, null);
		this.setContentView(viewToLoad);
		// init
		init();
		// get info from intent
		getInfoFromIntent();
	}

	public void init()
	{	getDataForSpinner();
		addSpinnerListener();
		// connect to view in xml
		connectXmlViews();
		// connect to change Button
		connectChangeButton();
		// add listener for add and cancel button
		AddListenerForAddCancelButton();
	}
	
	//-------- connect xml views
	TableRow smsAddDateRow,
		smsAddWeekCheckbox;
	TextView tvSmsAddPhone,
		tvSmsAddContent;
	CheckBox[] cbWeek = new CheckBox[7];
	public void connectXmlViews()
	{	// connect table rows
		smsAddDateRow = (TableRow) findViewById(R.id.smsAddDateRow);
		smsAddWeekCheckbox = (TableRow) findViewById(R.id.smsAddWeekCheckbox);
		// default visible cho vai row
		smsAddWeekCheckbox.setVisibility( View.GONE);

		// connect textview
		tvSmsAddPhone = (TextView) findViewById( R.id.tvSmsAddPhone);
		tvSmsAddContent = (TextView) findViewById(R.id.tvSmsAddContent);
		
		//connect weeks checkbox
		for( int i=0; i<cbWeek.length; i++)
			cbWeek[i] = new CheckBox(this);
		cbWeek[0] = (CheckBox) findViewById( R.id.cbSmsAddMon);	
		cbWeek[1] = (CheckBox) findViewById( R.id.cbSmsAddTue);	
		cbWeek[2] = (CheckBox) findViewById( R.id.cbSmsAddWed);	
		cbWeek[3] = (CheckBox) findViewById( R.id.cbSmsAddThu);	
		cbWeek[4] = (CheckBox) findViewById( R.id.cbSmsAddFri);	
		cbWeek[5] = (CheckBox) findViewById( R.id.cbSmsAddSat);	
		cbWeek[6] = (CheckBox) findViewById( R.id.cbSmsAddMon);	
	}
	
	//========= connect to change button, and time date textView
	Button btSmsAddDateChange,
		btSmsAddTimeChange;
	TextView tvSmsAddDate, tvSmsAddTime;
	int day, month, year, hour, minute, ampm;
	final int DIALOG_DATE = 1, DIALOG_TIME = 2;
	
	public void connectChangeButton()
	{	btSmsAddDateChange = (Button) findViewById(R.id.btSmsAddDateChange);
		btSmsAddTimeChange = (Button) findViewById( R.id.btSmsAddTimeChange);
		// textView
		tvSmsAddDate = (TextView) findViewById( R.id.tvSmsAddDate);
		tvSmsAddTime = (TextView) findViewById( R.id.tvSmsAddTime);
		//set default current date time for textView
		Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		//set to date text view
		tvSmsAddDate.setText(""+day+"/"+month+"/"+year);
		// for time
		hour = c.get( Calendar.HOUR);
		minute = c.get(  Calendar.MINUTE);
		ampm = c.get( Calendar.AM_PM);
		//set to time textView
		tvSmsAddTime.setText(""+hour+":"+minute+":"+ ((ampm==0)? "AM" : "PM"));	
		
		//add listener for button
		addListenerForDateTimeButton();
	}
	
	public void addListenerForDateTimeButton()
	{	btSmsAddDateChange.setOnClickListener( new OnClickListener()
		{	@Override
			public void onClick(View v)
			{	showDialog( DIALOG_DATE);				
			}
		});
		btSmsAddTimeChange.setOnClickListener( new OnClickListener()
		{	@Override
			public void onClick(View v)
			{	showDialog( DIALOG_TIME);				
			}
		});
	}
	
	// =============add listenner for change date time button==========
	@Override
	protected Dialog onCreateDialog(int id)
	{	switch (id)
		{	case DIALOG_DATE://click on date change button
				// set date picker as current date
				//return new DatePickerDialog(this, datePickerListener, year, month, day);
			/*chu y, vi cai acti nay trong group nen khong truyen this, ma truyen getparent()*/
				return new DatePickerDialog(getParent(), datePickerListener, year, month, day);
			case DIALOG_TIME://click on time change button
				// ampm = c.get... , ampm=0 ~~AM, =1 ~~PM
				return new TimePickerDialog(getParent(), timePickerListener, hour, minute, false);
		}
		return null;
	}
	/*o day viet lai mot OnDateSetListener de lam doi tuong 
	 * return ben trong ham onCreateDialog*/
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener()
	{	public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay)
		{	// when user finish choose date, this command will be call
			day = selectedDay;
			month = selectedMonth;
			year = selectedYear;
			// reset date for textView
			tvSmsAddDate.setText(""+day+"/"+month+"/"+year);
		}
	};
	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener()
	{	public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute)
		{	//Log.i(" Hour = ", ""+selectedHour);
			minute = selectedMinute;
			if( selectedHour > 12)
			{	hour = selectedHour - 12;
				ampm = 1;
			}
			else
			{	hour = selectedHour;
				ampm = 0;
			}
			//reset time for textView
			tvSmsAddTime.setText(""+hour+":"+minute+":"+ ((ampm==0)? "AM" : "PM"));	
		}	
	};
	
	
	//--------- get data spinner--------
	Spinner typeSpinner;
	//Spinner scheduleSpinner;
	Spinner soundSpinner;
	
	public void getDataForSpinner()
	{	// connect spinner
		typeSpinner = (Spinner) findViewById(R.id.smsAddTypeSpinner);
		soundSpinner = (Spinner) findViewById( R.id.smsAddSoundSpinner);
		//setdefault checked for spinner
		typeSpinner.setSelection( 0);//oneTime
		
		// typeSpinner
		ArrayAdapter<CharSequence> spinnerAdapter1 = ArrayAdapter.createFromResource
			( this, R.array.smsAddSpinnerString, android.R.layout.simple_spinner_item);
		spinnerAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		typeSpinner.setAdapter(spinnerAdapter1);
		
		//Schedule sound spinner
		ArrayAdapter<CharSequence> spinnerAdapter3 = ArrayAdapter.createFromResource
			( this, R.array.activity_tasks_add_lstsound, android.R.layout.simple_spinner_item);
		spinnerAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		soundSpinner.setAdapter(spinnerAdapter3);
	}
	
	//--------- set spinner listener---------
	public void addSpinnerListener()
	{	//type spinner
		typeSpinner.setOnItemSelectedListener( new OnItemSelectedListener()
		{	@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItem, int position, long id)
			{	switch (position)
				{	case 0: //onetime
						smsAddWeekCheckbox.setVisibility(View.GONE);
						smsAddDateRow.setVisibility( View.VISIBLE);
						break;
					case 1:// Schedule
						smsAddWeekCheckbox.setVisibility(View.VISIBLE);
						smsAddDateRow.setVisibility( View.GONE);
						break;
				}
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0)
			{
			}
		});

		//sound spinner khong can
	}
	
	
	//========= add listener for Add and cancel button========
	
	Button btSmsAddAdd, btSmsAddCancel;
	public void AddListenerForAddCancelButton()
	{	//connect
		btSmsAddAdd = (Button) findViewById( R.id.btSmsAddAdd);
		btSmsAddCancel = ( Button) findViewById( R.id.btSmsAddCancel);
		// add listener
		btSmsAddAdd.setOnClickListener( new OnClickListener()
		{	public void onClick(View arg0)
			{	if( !isEdit)
				{	// create sms to insert to database
					SmsMainItem item = getInfoFromViews();
					//----- add to database-----
					SmsMainDAO.getInstance().addSMS(item);
					//---- turn back to main SMS
					finish();
				}
				else //edit an item
				{	SmsMainItem item = getInfoFromViews();
					SmsMainDAO.getInstance().updateSMSByID(smsId, item);
					finish();
				}
			}
		});
		// cancel
		btSmsAddCancel.setOnClickListener( new OnClickListener()
		{	public void onClick(View arg0)
			{	if(isEdit)// delete
				{	SmsMainDAO.getInstance().deleteSMSByID(smsId);
				}
				finish();
			}
		});
	}
	
	public SmsMainItem getInfoFromViews()
	{	SmsMainItem item = new SmsMainItem();
		boolean isOneTime = typeSpinner.getSelectedItemPosition()==0 ;
		// get basic info
		item.setOneTime( isOneTime);
		item.setContent( tvSmsAddContent.getText().toString());
		item.setPhone( tvSmsAddPhone.getText().toString());
		item.setTime(tvSmsAddTime.getText().toString());
		item.setSound( soundSpinner.getSelectedItemPosition());
		// oneTime or Schedule
		if( isOneTime)//ontime
		{	item.setDate( tvSmsAddDate.getText().toString());
		}
		else// schedule
		{	String str = "";
			for( int i=0; i<cbWeek.length; i++)
				if( cbWeek[i].isChecked()) 
				{	//str.concat(" "+i);
					str += i; str+=" ";
				}
			item.setWeekDays(str.trim());
		}
		return item;
	}
	
	//======== get info from intent======
	public void getInfoFromIntent()
	{	Intent intent = getIntent();
		String AddOrEdit = intent.getStringExtra("AddOrEdit");
	
		if( AddOrEdit.equals("edit"))
		{	Bundle bundle = intent.getExtras();
			SmsMainItem item = (SmsMainItem)bundle.getSerializable("sms");
			//set data for views
			tvSmsAddPhone.setText(item.getPhone());
			tvSmsAddContent.setText(item.getContent());
			tvSmsAddTime.setText(item.getTime());
			soundSpinner.setSelection(item.getSound());
			
			// change text for button
			isEdit = true;
			smsId = item.getId();
			changeTextForButton();
			
			// onetime and schedule
			if(item.isOneTime())
			{	//oneTime
				typeSpinner.setSelection(0);
			}
			else //schedule
			{	typeSpinner.setSelection(1);
				smsAddDateRow.setVisibility(View.GONE);
				smsAddWeekCheckbox.setVisibility(View.VISIBLE);
				//tick for checkbox
				tickForWeekCheckbox(item.getWeekDays().split(" "));
			}
		}
	}
	
	public void changeTextForButton()
	{	btSmsAddAdd.setText("OK");
		btSmsAddCancel.setText("Delete");
	}
	
	public void tickForWeekCheckbox(String[] days)
	{	int num = days.length;
		int[] day = new int[num];
		for( int i=0; i<num; i++)
			day[i] = Integer.parseInt(days[i]);
		//tick
		for( int i=0; i<num; i++)
			cbWeek[day[i]].setChecked(true);
	}
	
	//===================
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{	getMenuInflater().inflate(R.menu.activity_smsactivity_add, menu);
		return true;
	}
	
}
